package com.yiban.demo.Global.ServletComponent;

import com.yiban.demo.LoginUser.Controller.LoginUserController;
import com.yiban.demo.LoginUser.Entity.LoginUserPO;
import com.yiban.demo.LoginUser.Entity.ROLE;
import com.yiban.demo.Global.Entity.ResponseEntity;
import com.yiban.demo.Access.Entity.RestfulUri;
import com.yiban.demo.Access.Service.AccessService;
import com.yiban.demo.Util.JsonUtil;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class UriControlFilter extends OncePerRequestFilter {

    private AccessService accessService;

    public UriControlFilter(AccessService accessService) {
        this.accessService = accessService;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        final String patternPath = accessService.patternPath(httpServletRequest.getRequestURI());

        //uri是否存在
        if (patternPath == null){
            ResponseEntity.writeBack(httpServletResponse, JsonUtil.defaultJsonify(ResponseEntity.Failure(404, "uri无匹配")));
            return;
        }

        //利用本次请求的数据获取access对象
        LoginUserPO user = (LoginUserPO) httpServletRequest.getSession().getAttribute(LoginUserController.USER_SESSION_KEY);
        String nowRole;
        if (user == null){
            nowRole = ROLE.EVERYBODY.getName();
        }else {
            nowRole = user.getRole();
        }
        RestfulUri uri = new RestfulUri(patternPath,httpServletRequest.getMethod());

        //判断此次uri是否允许访问
        if (accessService.getAllAccess().get(nowRole).contains(uri)){
            filterChain.doFilter(httpServletRequest,httpServletResponse);
            return;
        }

        ResponseEntity.writeBack(httpServletResponse, JsonUtil.defaultJsonify(ResponseEntity.Failure("权限不足")));
    }


}
